const MyclassList = require("./ie9-classlist.js");
const qiniu = require("./qiniu.min.js");

function IolFileup(opts) {
	this.initData(opts);
};

IolFileup.prototype.initData = function(opts){
	if(!opts.token){ console.log("请提供 token ~");return false; }
	if(!opts.el || opts.el.nodeType != 1){ console.log("请提供 容器元素~");return false; }
	// Dom
	this.ctn = opts.el; 								// 容器元素
	this.createBtnId(); 								// 为上传按钮创建Id
	
	this.token = opts.token;
	this.Bucket = opts.Bucket ? opts.Bucket : "transn-test";
	this.domain = opts.domain ? opts.domain : "http://p3eom0r71.bkt.clouddn.com";
	this.maxFileSize = opts.maxFileSize ? opts.maxFileSize : 100;
	this.files = [];
	this.success = (typeof opts.success == "function") ? opts.success : null;
	this.error   = (typeof opts.error == "function") ? opts.error : null;
	
	// 样式: double 是双列文件
	this.double = opts.double ? opts.double : false;
	// html中
	this.des1 = opts.des1 ? opts.des1 : "拖拽上传";
	this.des2 = opts.des2 ? opts.des2 : "或";
	this.des3 = opts.des3 ? opts.des3 : "点击上传";
	this.des4 = opts.des4 ? opts.des4 : "支持单个或多个 txt、doc、pdf 等格式文件；文件大小≤" + this.maxFileSize;
	this.initHtml();
	this.fileUl = this.ctn.querySelector(".file-ul");	// 文件上传列表
	
	this.uploader = this.createUploader();
};

IolFileup.prototype.createIolId = function(id){
	// 实例个数
	if(!IolFileup.prototype.iolId){
		IolFileup.prototype.iolId = 1;
	}else{
		IolFileup.prototype.iolId += 1;
	}
};

IolFileup.prototype.createBtnId = function(id){
	// 由于七牛的uploader需要id, 故每次生成实例时, 要产生
	// 2个id: btn-upload(上传按钮), btn-form(上传区域)
	this.createIolId();
	
	// 上传按钮id
	this.uploadBtnId = "btn-upload" + IolFileup.prototype.iolId;
	// 上传区域id
	this.uploadFormId = "upload-form" + IolFileup.prototype.iolId;
};

IolFileup.prototype.getItemById = function(id){
	// 通过id 从文件列表中获取文件对象
	var i, item, len = this.files.length;
	for(i = 0; i < len; i++){
		item = this.files[i];
		if(item.id == id){
			return {i: i, item: item};
		}
	}
	return null;
};

IolFileup.prototype.removeFileById = function(id){
	// 通过id 从文件列表中获取文件对象
	var i, item, len = this.files.length;
	for(i = 0; i < len; i++){
		item = this.files[i];
		if(item.id == id){
			this.files.splice(i, 1);
			return;
		}
	}
};

IolFileup.prototype.initHtml = function(){
	this.initCss();

	var doubleClass = this.double ? 'double' : '';
	var div = document.createElement("div");
	div.className = "fileupload-ctn";
	div.innerHTML = '<div class="upload-form" id="'+ this.uploadFormId +'"><div class="upload-header"><b class="drag-tip">'
		+ this.des1 + '</b> ' + this.des2 + ' <span class="btn-upload" id="'+ this.uploadBtnId +'"> '
		+ this.des3 + '</span></div><p class="upload-desc">'+ this.des4 +'</p></div><ul class="file-ul '
		+ doubleClass +'" id="file-ul"></ul>';
	
	this.ctn.appendChild(div);
};

IolFileup.prototype.initCss = function(){
	var css = '.fileupload-ctn{position:relative;display:block;min-width:800px;box-sizing:border-box;margin:20px auto;padding:24px 20px;font:12px/1.3 "microsoft yahei";color:#333;border-radius:4px;background:#fff}.fileupload-ctn .upload-form{padding:28px 0 18px;line-height:32px;color:grey;text-align:center;border-radius:6px;border:1px dashed #a7b5cb;background:#f4f9ff}.fileupload-ctn .upload-header{font-size:14px}.fileupload-ctn .drag-tip{display:inline-block;padding-left:40px;margin-right:5px;vertical-align:top;color:#333;background:url(../images/fileup-upload.png) no-repeat left center}.fileupload-ctn .btn-upload{display:inline-block;margin-left:5px;padding:0 26px;vertical-align:top;color:#fff;border-radius:16px;background:#015bf1;cursor:pointer}.fileupload-ctn .upload-desc{margin:0}.fileupload-ctn .file-ul{list-style:none;width:65%;max-height:210px;box-sizing:border-box;margin:0 auto;padding:6px 20px 6px 0;line-height:20px;overflow-y:auto}.fileupload-ctn .file-ul::-webkit-scrollbar{width:4px}.fileupload-ctn .file-ul::-webkit-scrollbar-track{background:#f8f8f8}.fileupload-ctn .file-ul::-webkit-scrollbar-thumb{background:#dadada;border-radius:2px}.fileupload-ctn .file-ul:after{content:"";display:block;clear:both}.fileupload-ctn .file-ul.double{width:100%}.fileupload-ctn .file-ul.double>li{display:inline-block;width:47%;box-sizing:border-box;float:left}.fileupload-ctn .file-ul.double>li:nth-child(2n+2){float:right}.fileupload-ctn .file-ul>li{padding:10px 16px;border-bottom:1px solid #f0f0f0;word-spacing:-5px}.fileupload-ctn .file-name,.fileupload-ctn .words-count{display:inline-block;box-sizing:content-box;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;word-spacing:normal;vertical-align:top}.fileupload-ctn .file-name{width:40%;padding-right:7%}.fileupload-ctn .file-name:before{content:"";display:inline-block;width:6px;height:6px;margin-right:8px;margin-top:7px;vertical-align:top;border-radius:50%;background:#ababab}.fileupload-ctn .progress-wrap{display:inline-block;width:30%;box-sizing:border-box;padding-right:7%}.fileupload-ctn .progress-bar{display:inline-block;width:45%;height:6px;margin-right:4%;margin-top:7px;vertical-align:top;border-radius:3px;background:#e5e5e5;overflow:hidden}.fileupload-ctn .progress-bar .in{display:block;float:left;height:100%;background:#abb5c5}.fileupload-ctn .progress-per{display:inline-block;width:50%;color:grey}.fileupload-ctn .words-count{width:15%}.fileupload-ctn .btn-close{float:right;width:20px;height:20px;background:url(../images/close.png) no-repeat 50% 0;cursor:pointer}.fileupload-ctn .btn-close:hover{background-position:0 -30px}'; 
	
	if(document.all){ 
        window.style = css; 
        document.createStyleSheet("javascript:style"); 
    }else{ 
        var style = document.createElement('style'); 
        style.type = 'text/css'; 
        style.innerHTML = css; 
        document.getElementsByTagName("head")[0].appendChild(style); 
    } 
};

IolFileup.prototype.getFiles = function(){
	return this.files;
};

IolFileup.prototype.createUploader = function(){
	var that = this,
		opts = 	{
		  	runtimes: 'html5',    
		  
		  	browse_button: this.uploadBtnId,         	
		  	drop_element: this.uploadFormId,         
		  	container: this.uploadFormId,            
		  
		  	uptoken : that.token, 				
		  	get_new_uptoken: false,
		  
		  	domain: that.domain,
		  	max_file_size: that.maxFileSize + "mb",             
		  	max_retries: 3, 
		  	chunk_size: '4mb', 
		  	auto_start: true,
		  	init: {
		        'FilesAdded': function(up, files) {
		            plupload.each(files, function(file) {
		                // 文件添加进队列后，处理相关的事情
		                var li = document.createElement("li");
		                li.setAttribute("data-id", file.id);
		                li.innerHTML = '<span class="btn-close"></span><span class="file-name">'+ file.name +'</span><span class="progress-wrap"><span class="progress-bar"><span class="in" style="width: 0;"> </span></span><span class="progress-per">0%</span></span><span class="words-count"></span>';
		                that.fileUl.appendChild(li);
		                  
		                that.files.push({
		              		id: file.id,
		              		oldName: file.name,
		              		newName: "",
		              		status: "waiting",
		              		downloadUrl: ""
			            });
		            });
		              
		            // 绑定移出事件
		            if(!that.fileUl.getAttribute("data-event")){
		              	that.fileUl.setAttribute("data-event", "true");
		              	 
		              	that.fileUl.addEventListener("click", function(e){
		      	 			var eTar = e.target;
		      	 			if(eTar.classList.contains("btn-close")){
		      	 				// 1 从 文件列表 中移出此对象
		      	 				var li2 = eTar.parentNode;
		      	 				var fileId = li2.getAttribute("data-id");
		      	 				that.removeFileById(fileId);
		      	 				// 2 从网页上删除
		      	 				li2.parentNode.removeChild(li2);
		      	 				//3 从 七牛服务器 中移出此文件(次功能暂未实现)
		      	 			}
		              	});
		            }
		        },
		      	'BeforeUpload': function(up, file) {
		      		if(parseInt(file.origSize/1024/1024) >= that.maxFileSize){
		      			return false;
		      		}
		      	},
		      	'UploadProgress': function(up, file) {
		  			var	li = that.fileUl.querySelector("[data-id='"+ file.id +"']");
		      					
		            if(li){
		        		li.querySelector(".in").style.width = file.percent + "%";
		        		li.querySelector(".progress-per").innerHTML = file.percent + "%";
		            }
		            
		          	var index = that.getItemById(file.id);
		      		if(index){
		  				that.files[index.i].status = "sending";
		      		}
		      	},
		      	'FileUploaded': function(up, file, info) {
		      		var index = that.getItemById(file.id),
		      			curFile = that.files[index.i];
		      		if(index){
		  				that.files[index.i].status = "success";
		  				that.files[index.i].downloadUrl = that.domain + "/" + curFile.newName + "?attname=" + curFile.oldName;
		      		}
		      		
					var li = that.fileUl.querySelector("[data-id='"+ file.id +"']");
		            if(li){
		        		li.querySelector(".progress-per").innerHTML = "成功";
		            }
		            
		            if(that.success){ that.success(curFile); }
		      	},
		        'Error': function(up, err, errTip) {
		          	if(that.error){ that.error(err, errTip); }
		        },
		        'UploadComplete': function() {
		          		
		        },
		        'Key': function(up, file) {
	          		var names = file.name.split("."),
	          				extName = names.length > 0 ? names[names.length - 1] : "";
	          		var key = Date.now() + "_" + parseInt(Math.random()*1000) + "." + extName;		
	          	
	          		var index = that.getItemById(file.id);
	          		if(index){
	          				that.files[index.i].newName = key;
	          		}
	          		return key;
		        }
		    }
		};
	
	if(this.iolId == 1){
		return Qiniu.uploader(opts);
	}else{
		// 超过2个实例
		return new QiniuJsSDK().uploader(opts);
	}
};

window.IolFileup = IolFileup;

